package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.CheckgroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.*;
import com.itheima.pojo.dto.SetmealDto;
import com.itheima.pojo.vo.CheckGroupVo;
import com.itheima.pojo.vo.CheckItemVo;
import com.itheima.service.CheckgroupService;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckgroupMapper checkgroupMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private Configuration configuration;

    /**
     * 新增套餐
     * @param setmealDto
     */
    @Override
    public void add(SetmealDto setmealDto, String checkgroups) {
        SetmealPojo setmealPojo = new SetmealPojo();
        BeanUtils.copyProperties(setmealDto, setmealPojo);

        String[] split = checkgroups.split(",");
        List<Integer> checkgroupIds = new ArrayList<>();
        for (String s : split) {
            //将s存储到checkgroupIds中
            checkgroupIds.add(Integer.parseInt(s));
        }

        List<CheckGroupVo> checkGroups = checkgroupMapper.ByList(checkgroupIds);
        BigDecimal cost = new BigDecimal(0);
        for (CheckGroupVo checkGroup : checkGroups) {
            cost = cost.add(BigDecimal.valueOf(checkGroup.getCost()));
        }
        setmealPojo.setCost(cost.doubleValue());
        setmealPojo.setCheckGroups(checkgroups);
        setmealPojo.setCreateTime(LocalDateTime.now());
        setmealPojo.setUpdateTime(LocalDateTime.now());

        setmealMapper.add(setmealPojo);
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmealPojo.getImg());
        //生成静态页面文件
        try {
            generateSetmealListPage();
            generateSetmealDetailPages();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 删除套餐
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        setmealMapper.deleteById(id);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     */
    @Override
    public void update(SetmealDto setmealDto, String checkgroups) {
        SetmealPojo setmealPojo = new SetmealPojo();
        BeanUtils.copyProperties(setmealDto, setmealPojo);

        String[] split = checkgroups.split(",");
        List<Integer> checkgroupIds = new ArrayList<>();
        for (String s : split) {
            //将s存储到checkgroupIds中
            checkgroupIds.add(Integer.parseInt(s));
        }

        List<CheckGroupVo> checkGroups = checkgroupMapper.ByList(checkgroupIds);
        BigDecimal cost = new BigDecimal(0);
        for (CheckGroupVo checkGroup : checkGroups) {
            cost = cost.add(BigDecimal.valueOf(checkGroup.getCost()));
        }
        setmealPojo.setCost(cost.doubleValue());
        setmealPojo.setCheckGroups(checkgroups);

        setmealPojo.setUpdateTime(LocalDateTime.now());
        setmealMapper.update(setmealPojo);

    }



    /**
     * 生成套餐列表静态页面
     */
    public void generateSetmealListPage() throws Exception {
        // 查询所有套餐
        List<SetmealPojo> setmealList = setmealMapper.findAll();

        // 转换为前端需要的 Setmeal 对象
        List<Setmeal> setmeals = new ArrayList<>();
        for (SetmealPojo setmealPojo : setmealList) {
            Setmeal setmeal = new Setmeal();
            BeanUtils.copyProperties(setmealPojo, setmeal);
            setmeals.add(setmeal);
        }

        // 准备数据模型
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("list", setmeals);

        // 获取模板
        Template template = configuration.getTemplate("mobile_setmeal.ftl");

        // 生成静态页面文件
        String filePath = "E:/code/setmeal_list.html";
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        FileWriter out = new FileWriter(file);
        template.process(dataModel, out);
        out.close();

        log.info("套餐列表静态页面生成成功: {}", filePath);
    }

    /**
     * 生成套餐详情静态页面（多个）
     */

    public void generateSetmealDetailPages() throws Exception {
        // 查询所有套餐
        List<SetmealPojo> setmealList = setmealMapper.findAll();

        // 为每个套餐生成详情页面
        for (SetmealPojo setmealPojo : setmealList) {
            // 获取包含检查组详情的套餐信息
            SetmealPojo detailSetmeal = getById(setmealPojo.getId());

            // 准备数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("setmeal", detailSetmeal);

            // 获取模板
            Template template = configuration.getTemplate("mobile_setmeal_detail.ftl");

            // 生成静态页面文件
            String filePath = "E:/code/setmeal_detail_" + setmealPojo.getId() + ".html";
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            FileWriter out = new FileWriter(file);
            template.process(dataModel, out);
            out.close();

            log.info("套餐详情静态页面生成成功: {}", filePath);
        }
    }

    /**
     * 分页查询套餐
     *
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<SetmealPojo> page = setmealMapper.findPage(queryPageBean);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询所有套餐
     *
     * @return
     */
    @Override
    public List<SetmealPojo> findAll() {
        List<SetmealPojo> setmeals = setmealMapper.findAll();
        return setmeals;
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public SetmealPojo getById(Integer id) {
        SetmealPojo setmealPojo = setmealMapper.getById(id);
        if (setmealPojo != null) {
            String checkGroupIds = setmealPojo.getCheckGroups();
            //将字符串转换成Integer集合
            String[] split = checkGroupIds.split(",");
            List<Integer> list = new ArrayList<>();
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
            List<CheckGroupPojo> checkGroups = checkgroupMapper.ByListId(list);
            setmealPojo.setCheckGroupIds(checkGroups);
            return setmealPojo;
        }
        return null;
    }

    @Override
    public Setmeal findById(Integer id) {
        return null;
    }


    /* *//**
         * 用户端根据id查询套餐
         * @param id
         * @return
         *//*
    @Override
    public Setmeal findById(Integer id) {
        SetmealPojo setmealPojo = setmealMapper.getById(id);

        if (setmealPojo != null){
            Setmeal setmeal = new Setmeal();
            BeanUtils.copyProperties(setmealPojo,setmeal);
            String checkGroupIds = setmealPojo.getCheckGroups();
            //将字符串转换成Integer集合
            String[] split = checkGroupIds.split(",");
            List<Integer> list = new ArrayList<>();
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
            List<CheckGroupPojo> checkGroups = checkgroupMapper.ByListId(list);


            for (CheckGroupPojo checkGroup : checkGroups) {
                List<CheckItemVo> checkItemVos = checkItemMapper.getById(checkGroup.getId());
                checkGroup.setCheckItems(checkItemVos);
            }
            setmeal.setCheckGroups(checkGroups);
            return setmeal;
        }
        return null;
    }*/

        /**
         * 查询所有套餐
         * @return
         */
    @Override
    public List<Setmeal> getAll() {
        List<Setmeal> setmeals = setmealMapper.getAll();
        return setmeals;
    }

  /*  public void generateStaticPages() {
        try {
            // 生成套餐列表页面
            generateSetmealListPage();

            // 生成套餐详情页面
            generateSetmealDetailPages();
        } catch (Exception e) {
            log.error("生成静态页面失败", e);
            throw new RuntimeException("生成静态页面失败", e);
        }
    }*/
    }

